package com.acme.concurrent.indexer;

import java.io.File;
import java.io.FileFilter;

/**
 * @author Gregory Sobko
 */
class FileCrawler implements Runnable {
    private final FileQueuePool fileQueue;
    private final FileFilter fileFilter;
    private final File root;


    public FileCrawler(FileQueuePool fileQueue,
                       final FileFilter fileFilter,
                       File root) {
        this.fileQueue = fileQueue;
        this.root = root;
        this.fileFilter = new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || fileFilter.accept(f);
            }
        };
    }

    private boolean alreadyIndexed(File f) {
        return false;
    }

    public void run() {
        try {
            crawl(root);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } catch (IllegalStateException e){
            System.err.println("Queue pool is closed! Cannot put any files in it =(");
        }finally {
            fileQueue.signalProducerDone();
            System.out.println("Crawler for root "+ root.getPath() + " is done!");
        }
    }

    private void crawl(File root) throws InterruptedException {
        File[] entries = root.listFiles(fileFilter);
        if (entries != null) {
            for (File entry : entries)
                if (entry.isDirectory())
                    crawl(entry);
                else if (!alreadyIndexed(entry))
                    fileQueue.put(entry);
        }

    }
}
